import { useEffect, useMemo, useRef, useState } from "react";
import {
  addUser,
  updateUser,
  listUser,
  delUser,
  exportUser,
  importTemplate,
  enableUser,
  disableUser,
  lockUser,
  unlockUser
} from '@/api/system/user'

import SearchForm from "../../../components/searchForm";
import { Table, Divider, Button, message, Modal, Form, Flex, Space, Typography, Avatar, Badge } from "antd";
import { keepPreviousData, useQueries, useQuery } from "@tanstack/react-query";
import { ModalForm } from "@ant-design/pro-components";
import { PlusOutlined, ExclamationCircleFilled, DoubleLeftOutlined, DoubleRightOutlined } from '@ant-design/icons';
import { useThemeToken } from "@/theme/hooks";
import UserForm from "./modules/userForm";
import SelectDeptTree from "../dept/modules/selectDeptTree";
import { useDictionary } from "@/hooks";
import DisplayLabel from "@/components/displayLabel";
import { download, rangeQueryNormalize } from "@/utils";
import ResetPasswordModal from "./modules/resetPasswordModal";
import UserPermissionModal from "./modules/userPermissionModal";
import styled from 'styled-components'
import { m } from "framer-motion";
import ImportExcelModal from "./modules/ImportExcelModal";

const colorList = ['#F38709', '#813AFD', '#00C4AA', '#4B7AEE']

const queryItems = [
  {
    name: 'name',
    label: '姓名',
    type: 'INPUT',
  },
  {
    name: 'userName',
    label: '用户名',
    type: 'INPUT',
  },
  {
    name: 'phonenumber',
    label: '手机号',
    type: 'INPUT',
  },
  {
    name: 'status',
    label: '状态',
    type: 'SELECT',
    dictType: 'user_status',
  },
  {
    name: 'beginTime-endTime',
    label: '创建时间',
    type: 'RANGE_PICKER',
  }
];


const SliderTrigger = ({ onChange, value }) => {
  const { colorBorder, colorBgBase } = useThemeToken()
  const StyledDiv = styled.div`
  &.slider-trigger{
    position: absolute;
  width: 20px;
  height: 30px;
  top: 16px;
  left: ${value ? '-19px' : '-1px'};
  text-align: center;
  line-height: 30px;
  border: ${colorBorder} solid 1px;
  background-color: ${colorBgBase};
  border-width: ${value ? '1px 0px 1px 1px' : '1px 1px 1px 0'};
  cursor: pointer;
  }
`
  return (
    <StyledDiv
      className="slider-trigger"
      onClick={() => onChange(!value)}
    >
      {value ? <DoubleLeftOutlined /> : <DoubleRightOutlined />}
    </StyledDiv >
  )
}

const StyleSelectDeptTree = styled.div`
  .ant-input-search{
    padding-right: 20px;
  }
`


//i18n
const UserIndex = () => {
  const userPermissionModalRef = useRef()
  const importExcelModalRef = useRef()
  const [deptNode, setDeptNode] = useState()
  const [queryParam, setQueryParam] = useState({});
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState([]);
  const [page, setPage] = useState({ pageNo: 1, pageSize: 10 });
  const [sliderShow, setSliderShow] = useState(true)
  const confirm = Modal.confirm;
  const { colorBorder } = useThemeToken();
  useDictionary(['user_status', 'sys_normal_disable']);
  const columns = [
    {
      title: '用户名',
      dataIndex: 'userName',
      width: 120
    },
    {
      title: '姓名',
      dataIndex: 'name',
      width: 200,
      render: (text, record, idx) => (<>
        <ModalForm
          trigger={
            <a>
              <Space size={8}>
                <Avatar shape="square" style={{ backgroundColor: colorList[idx % 4] }}>
                  {text.slice(0, 2)}
                </Avatar>
                {text}
              </Space>
            </a>
          }
          title={'修改【' + record.name + '】信息'}
          modalProps={{ destroyOnClose: true }}
          onFinish={saveData}
          initialValues={{
            ...record
          }}
          grid={true}
        >
          <UserForm userId={record.id} />
        </ModalForm>
      </>)
    },
    {
      title: '组织',
      dataIndex: ['sysDept', 'deptName'],
      width: 150
    },
    // {
    //   title: '专业',
    //   dataIndex: 'majorName',
    //   scopedSlots: { customRender: 'majorName' },
    //   width: 300
    // },
    {
      title: '用户状态',
      dataIndex: 'status',
      align: 'center',
      width: 100,
      render: (text) => (<Badge status={text == '0' ? 'processing' : 'error'} text={<DisplayLabel value={text} type="user_status" />} />)
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      width: 280,
      render: (_, record) => (
        <>
          <ModalForm
            trigger={<a>修改</a>}
            title={'修改【' + record.name + '】信息'}
            modalProps={{ destroyOnClose: true }}
            onFinish={saveData}
            initialValues={{
              ...record
            }}
            grid={true}
          >
            <UserForm userId={record.id} />
          </ModalForm>
          <Divider type="vertical" />
          <a onClick={() => {
            userPermissionModalRef.current.showModal(record)
          }}>权限管理</a>
          <Divider type="vertical" />
          <a onClick={() => { deleteConfirm(record) }}>删除</a>
          <Divider type="vertical" />
          <ResetPasswordModal onFinish={refetch} initialValues={{
            ...record
          }} />
        </>
      ),
    },
  ];

  const { data: tableData, isFetching, refetch } = useQuery({
    queryKey: ['page-user-listUser', queryParam, page],
    queryFn: () => {
      return listUser({
        pageNum: page.pageNo,
        pageSize: page.pageSize,
        ...rangeQueryNormalize(queryParam)
      }).then((res) => {
        return res.data || {}
      })
    },
    staleTime: 0,
    placeholderData: keepPreviousData,
  })

  const onSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys)
    setSelectedRows(selectedRows)
  }

  const saveData = (values) => {
    if (values.id) {
      return updateUser(values).then((res) => {
        if (res.code === 200) {
          refetch()
          message.success('修改成功')
          return true
        }
      })
    } else {
      return addUser(values).then((res) => {
        if (res.code === 200) {
          refetch()
          message.success('新增成功')
          return true
        }
      })
    }
  }

  const deleteConfirm = (row) => {
    const ids = row.id || selectedRowKeys
    const userNames = row.name || selectedRows.map(d => d.name)
    confirm({
      title: '确认删除所选中数据?',
      icon: <ExclamationCircleFilled />,
      content: '当前选中编号为' + userNames + '的数据',
      autoFocusButton: null,
      onOk() {
        return delUser(ids)
          .then(() => {
            onSelectChange([], [])
            refetch()
            message.success('删除成功')
          })
      },
      onCancel() { },
    });
  };

  const exportConfirm = () => {
    confirm({
      title: '是否确认导出?',
      content: '此操作将导出当前条件下所有数据而非选中数据',
      autoFocusButton: null,
      onOk() {
        return exportUser({
          pageNum: page.pageNo,
          pageSize: page.pageSize,
          ...queryParam,
        })
          .then(response => {
            download(response.msg)
            message.success('导出成功')
          })
      },
      onCancel() { },
    });
  }

  const onTreeChange = (value, info) => {
    setQueryParam({
      ...queryParam,
      deptId: value[0] || undefined
    })

    setDeptNode(info.selected ? info.node : undefined)
  }
  return (
    <Flex vertical={true} className="searchTableWrapper">
      <div className="searchTableHeader">用户管理</div>
      <Flex flex={1}
        style={{ borderTop: `1px solid ${colorBorder}` }}>
        <m.div
          style={{ borderRight: `1px solid ${colorBorder}`, flexShrink: 0 }}
          animate={sliderShow ? "open" : "closed"}
          variants={{
            open: {
              width: 220,
              transition: {
                type: "tween",
                duration: 0.3,
              },
            },
            closed: {
              width: 0,
              display: "none",
              transition: {
                type: "tween",
                duration: 0.3,
              },
            },
          }}
        >
          <StyleSelectDeptTree style={{ display: sliderShow ? 'block' : 'none', padding: '16px 10px' }}>
            <SelectDeptTree
              showSearch
              selectedKeys={[queryParam.deptId]}
              onSelect={onTreeChange} />
          </StyleSelectDeptTree>
        </m.div>

        <Flex flex={1} vertical style={{ position: 'relative' }}>
          <SliderTrigger value={sliderShow} onChange={setSliderShow} />
          <div style={{ padding: '16px 30px 0', borderBottom: `1px solid ${colorBorder}` }}>
            <SearchForm
              onSearch={(values) => setQueryParam({ ...queryParam, ...values })}
              items={queryItems}
              searchContent="查询"
            />
          </div>
          <div style={{ padding: '12px 16px' }}>
            <Flex style={{ padding: '12px 0' }} align="center" justify="space-between">
              <Typography.Title level={4}>
                {deptNode?.title || '用户管理'}
              </Typography.Title>
              <Space>
                <ModalForm
                  trigger={<Button icon={<PlusOutlined />} type="primary">新增</Button>}
                  title="新增用户"
                  modalProps={{ destroyOnClose: true }}
                  onFinish={saveData}
                  grid={true}
                  initialValues={{
                    sex: '2',
                    status: '0',
                    userType: '2',
                  }}
                >
                  <UserForm />
                </ModalForm>
                {selectedRowKeys.length > 0 && <Button danger onClick={deleteConfirm}>批量删除</Button>}
                <Button onClick={() => { importExcelModalRef.current.showModal() }}>导入</Button>
                <Button onClick={exportConfirm}>导出</Button>
              </Space>
            </Flex>

            <Table
              rowSelection={{ type: 'checkbox', selectedRowKeys: selectedRowKeys, onChange: onSelectChange }}
              columns={columns}
              rowKey={(record) => record.id}
              loading={isFetching}
              dataSource={tableData?.list || []}
              pagination={{
                current: page.pageNo,
                pageSize: page.pageSize,
                total: tableData?.total,
                onChange: (pageNo, pageSize) => {
                  setPage({ pageNo, pageSize })
                }
              }}
            />


          </div>
        </Flex>
      </Flex>
      <UserPermissionModal ref={userPermissionModalRef} />
      <ImportExcelModal ref={importExcelModalRef} onOk={refetch} />
    </Flex >
  );
};




export default UserIndex;
